import React from 'react';
import {RefreshControl, View, FlatList} from 'react-native';
import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import {BottomTabScreenProps} from '@react-navigation/bottom-tabs';
import {subjectArrs} from './consts';
import FlatListItem from '@/components/FlatListItem';
import {getFlatListData} from '@/mock';
import {type DataItem, useFlatListStore} from '@/store';
import {BottomTabParamList} from '..';

const Tab = createMaterialTopTabNavigator();

const PopularTab = () => {
  const store = useFlatListStore();
  const [loading, setLoading] = React.useState(false);

  const handleRefresh = () => {
    setLoading(true);
    setTimeout(() => {
      const listData = getFlatListData();
      store.setStore('data1', listData);
      setLoading(false);
    }, 1000);
  };

  const handleUpdate = ({index}: {index: number}) => {
    const newListData = [...store.data1];
    newListData[index].isSave = !newListData[index].isSave;
    store.setStore('data1', newListData);
  };

  return (
    <FlatList<DataItem>
      keyExtractor={item => item.id}
      data={store.data1}
      initialNumToRender={10}
      refreshControl={
        <RefreshControl
          title="加载中..."
          refreshing={loading}
          onRefresh={handleRefresh}
        />
      }
      renderItem={({item, index}) => (
        <FlatListItem
          source="Popular"
          index={index}
          value={item}
          handleUpdate={handleUpdate}
        />
      )}
    />
  );
};

const Popular: React.FC<
  BottomTabScreenProps<Pick<BottomTabParamList, 'Popular'>>
> = () => {
  const insets = useSafeAreaInsets();

  return (
    <View
      style={{
        flex: 1,
        marginTop: insets.top,
      }}>
      <Tab.Navigator>
        {subjectArrs.map((item, index) => (
          <Tab.Screen
            key={index}
            name={item}
            component={PopularTab}
            initialParams={{item}}
            options={{
              tabBarScrollEnabled: true,
              tabBarLabelStyle: {textTransform: 'capitalize'},
              tabBarIndicatorStyle: {
                height: 2,
              },
            }}
          />
        ))}
      </Tab.Navigator>
    </View>
  );
};

export default Popular;
